﻿using System;
using System.Collections.Generic;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory.Xml;
using Spring.Objects.Factory.Config;

namespace TinyERP.Framework
{
    public class ServiceLocator
    {
        private GenericApplicationContext context;
        private static ServiceLocator instance;
        private ServiceLocator()
        {
            if (context == null)
            {
                context = new GenericApplicationContext();
                XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(context);
                reader.LoadObjectDefinitions("file://ApplicationConfig/spring.xml");
            }
        }
        public GenericApplicationContext GetContext()
        {
            return context;
        }
        public static ServiceLocator GetInstance()
        {
            if (instance == null)
            {
                instance = new ServiceLocator();
            }
            return instance;
        }

        private object GetServiceInstance(string serviceName)
        {
            return context[serviceName];
        }

        public void RefreshContext()
        {
            context.Refresh();
            if (!context.IsRunning)
            {
                context.Start();
            }
        }
        public void RegisterObject(string name, IObjectDefinition objectDefinition)
        {
            context.RegisterObjectDefinition(name, objectDefinition);
        }

        public static object GetService(string serviceName)
        {
            return ServiceLocator.GetInstance().GetServiceInstance(serviceName);
        }


    }
}
